<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 发帖
 *
 * @author      Eden
 * @datetime    2016/12/9 00:43
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Post_Model extends API_Model
{
    /**
     * 参数
     * @var array
     */
    private $params = array();

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 主函数
     * @param array $params
     */
    public function run(Array $params)
    {
        $this->params = $params;
        $send['state'] = false;
        do {

            if (!$this->checkRequest()) {
                $send['error'] = $this->getError();
                break;
            }

            if ($posts = $this->postBbs()) {
                $send['state'] = true;
                $send['data'] = $posts;

                @statIncr('bbsIncr');
            } else {
                $send['error'] = $this->getError();
            }
        } while(false);
        $this->output->send($send);
    }

    /**
     * 发帖
     * @return array|bool
     */
    private function postBbs()
    {
        try {
            // bbs 表
            $this->load->helper('security');
            $content = xss_clean($this->params['content']);
            $content = strip_image_tags($content);
            $content = encode_php_tags($content);
            $bbsData = array(
                'userId' => $this->params['userId'],
                'content' => $content,
                'likes' => 0,
                'comments' => 0,
                'created' => dateTime(),
                'status' => 1
            );

            $bbsDb = clone($this->db);
            $bbsDb->trans_start();
            $bbsDb->insert('bbs', $bbsData);
            $bbsId = $bbsDb->insert_id();

            // bbs_attachement 表
            $bbsAttachment = array(
                'bbsId' => $bbsId,
                'attachment' => !empty($this->params['attachment']) ? json_encode($this->params['attachment']) : ''
            );
            $bbsDb->insert('bbs_attachment', $bbsAttachment);
            $bbsDb->trans_complete();

            if ($bbsDb->trans_status() === FALSE) {
                $this->setError('发帖失败');
                return false;
            }

            return array(
                'bbsId' => (int)$bbsId,
                'content' => $content,
                'attachment' => !empty($this->params['attachment']) ? bbsThumb($this->params['attachment'], $this->params['type']) : new stdClass(),
                'likes' => 0,
                'comments' => 0,
                'created' => formateTimeStamp($bbsData['created'])
            );

        } catch(PDOException $e) {
            $this->setError('发帖失败');
        } catch(Exception $e) {
            $this->setError('发帖失败');
        }
        $this->setError('发帖失败');
        return false;
    }

    /**
     * 检查参数
     * @return bool
     */
    private function checkRequest()
    {
        if ($this->input->method(true) !== 'POST') {
            $this->setError('非法请求');
            return false;
        }

        if (empty($this->params['userId'])) {
            $this->setError('用户未登录');
            return false;
        }

        if (empty($this->params['content'])) {
            $this->setError('评论内容不能为空');
            return false;
        }

        if (!isset($this->params['attachment'])) {
            $this->params['attachment'] = [];
        }

        if (!empty($this->params['attachment'])) {

            if (is_string($this->params['attachment'])) {
                $attachments = explode(',', $this->params['attachment']);
                $this->params['attachment'] = array_values($attachments);
            }

            if (count($this->params['attachment']) > 9) {
                $this->setError('图片数量超过限制');
                return false;
            }
        }
        return true;
    }
}